package com.backend.system.service.impl;

import com.backend.system.dao.entity.MenuRole;
import com.backend.system.dao.mapper.MenuRoleMapper;
import com.backend.system.service.IMenuRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * <p>
 * 菜单角色关系表 服务实现类
 * </p>
 *
 * @author backend-manage
 * @since 2024-04-02
 */
@Service
public class MenuRoleServiceImpl extends ServiceImpl<MenuRoleMapper, MenuRole> implements IMenuRoleService {

    /**
     * 通过角色ID查菜单
     *
     * @param roleId 角色ID
     * @return 菜单
     */
    @Override
    public List<MenuRole> getMenuRolesByRoleId(Long roleId) {
        LambdaQueryWrapper<MenuRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MenuRole::getRoleId, roleId);
        queryWrapper.orderByAsc(MenuRole::getId);

        List<MenuRole> menuRoles = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(menuRoles)) {
            return Collections.emptyList();
        }
        return menuRoles;
    }

    /**
     * 通过菜单ID查角色
     *
     * @param menuId 菜单ID
     * @return 角色
     */
    @Override
    public List<MenuRole> getMenuRolesByMenuId(Long menuId) {
        LambdaQueryWrapper<MenuRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MenuRole::getMenuId, menuId);
        queryWrapper.orderByAsc(MenuRole::getId);

        List<MenuRole> menuRoles = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(menuRoles)) {
            return Collections.emptyList();
        }
        return menuRoles;
    }

    /**
     * 通过菜单ID、角色ID删除角色菜单关联关系
     *
     * @param menuId 菜单ID
     * @param roleId 角色ID
     * @return 响应
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteMenuRole(Long menuId, Long roleId) {
        LambdaUpdateWrapper<MenuRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MenuRole::getMenuId, menuId);
        updateWrapper.eq(MenuRole::getRoleId, roleId);
        return this.remove(updateWrapper);
    }

    /**
     * 通过角色ID删除所有角色菜单关联关系
     *
     * @param roleId 角色ID
     * @return 响应
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean removeAllByRoleId(Long roleId) {
        LambdaUpdateWrapper<MenuRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(MenuRole::getRoleId, roleId);
        return this.remove(updateWrapper);
    }
}
